package com.eastdigit.bpm.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import net.sf.json.JSONObject;

import org.activiti.engine.delegate.Expression;
import org.activiti.engine.impl.javax.el.ELException;
import org.activiti.engine.impl.juel.AstBinary;
import org.activiti.engine.impl.juel.AstIdentifier;
import org.activiti.engine.impl.juel.AstLiteral;
import org.activiti.engine.impl.juel.ExpressionFactoryImpl;
import org.activiti.engine.impl.juel.ExpressionNode;
import org.activiti.engine.impl.juel.Tree;
import org.activiti.engine.impl.juel.TreeStore;
import org.springframework.stereotype.Service;

import com.eastdigit.bpm.model.NotEqualExpressionException;
import com.eastdigit.bpm.model.Variable;
import com.eastdigit.util.StringUtil;

/**
 * Created by Administrator on 2015/10/15.
 */
@Service(value = "expressionService")
public class ExpressionService extends ExpressionFactoryImpl {

    private final TreeStore store;

    public ExpressionService() {
        this(Profile.JEE6);
    }

    public ExpressionService(Profile profile) {
        Properties properties = loadProperties("el.properties");
        this.store = createTreeStore(1000, profile, properties);
    }

    public void addExpressionVariableKeys(List<Variable> list, String type, Expression expression) {
        if (expression != null) {
            Tree tree = store.get(expression.getExpressionText());
            for (String key : getVariables(tree.getRoot())) {
                list.add(new Variable(key, type));
            }
        }
    }

    public void addExpressionVariableKeys(List<Variable> list, String type, Map<String, Set<Expression>> Expressions) {
        if (Expressions != null) {
            for (Set<Expression> expressionSet : Expressions.values()) {
                addExpressionVariableKeys(list, type, expressionSet);
            }
        }
    }

    public void addExpressionVariableKeys(List<Variable> list, String type, Set<Expression> expressions) {
        if (expressions != null) {
            for (Expression expression : expressions) {
            	addExpressionVariableKeys(list, type, expression);
            }
        }
    }

    /**
     * 获取流程变量key
     * 
     * @param expressions
     * @return
     */
    public List<String> getExpressionVariableKeys(Set<Expression> expressions) {
        List<String> list = new ArrayList<String>();
        if (expressions != null) {
            for (Expression expression : expressions) {
                list.addAll(getExpressionVariableKeys(expression));
            }
        }
        return list;
    }

    /**
     * 获取流程变量key
     * 
     * @param expression
     * @return
     */
    public List<String> getExpressionVariableKeys(Expression expression) {
        Tree tree = store.get(expression.getExpressionText());
        return getVariables(tree.getRoot());
    }

    private List<String> getVariables(ExpressionNode node) {
        List<String> list = new ArrayList<String>();
        Object left = node.getChild(0);
        if (left != null) {
            if (left instanceof AstBinary) {// 还是表达式
                list.addAll(getVariables((AstBinary) left));
            } else if (left instanceof AstIdentifier) {// 是变量
                list.add(((AstIdentifier) left).getName());
            }
        }
        Object right = node.getChild(1);
        if (right != null) {
            if (right instanceof AstBinary) {// 还是表达式
                list.addAll(getVariables((AstBinary) right));
            } else if (right instanceof AstIdentifier) {// 是变量
                list.add(((AstIdentifier) right).getName());
            }
        }
        return list;
    }

    /**
     * 获取表达式中常量
     * 
     * @param conditionText
     * @return
     * @throws Exception
     */
    public JSONObject getExpressionConstantEqual(String conditionText) throws NotEqualExpressionException {
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isNotEmpty(conditionText)) {
            Map<String, Object> map = new HashMap<String, Object>();
            Tree tree = store.get(conditionText);
            dealExpressionConstantEqual(map, tree.getRoot());
            for (String key : map.keySet()) {
                jsonObject.put(key, map.get(key));
            }
        }
        return jsonObject;
    }

    private void dealExpressionConstantEqual(Map<String, Object> map, ExpressionNode node)
            throws NotEqualExpressionException {
        Object left = node.getChild(0);
        if (left != null) {
            Object left0 = ((AstBinary) left).getChild(0), left1 = ((AstBinary) left).getChild(1);
            if (left0 instanceof AstIdentifier && left1 instanceof AstLiteral) {
                if (!"==".equals(((AstBinary) left).getOperator().toString())) {
                    throw new NotEqualExpressionException();
                }
                map.put(((AstIdentifier) left0).getName(), left1.toString().substring(1, left1.toString().length() - 1));
            } else if (left1 instanceof AstIdentifier && left0 instanceof AstLiteral) {
                if (!"==".equals(((AstBinary) left).getOperator().toString())) {
                    throw new NotEqualExpressionException();
                }
                map.put(((AstIdentifier) left1).getName(), left0.toString().substring(1, left0.toString().length() - 1));
            } else {
                dealExpressionConstantEqual(map, (AstBinary) left);
            }
        }
        Object right = node.getChild(1);
        if (right != null) {
            Object right0 = ((AstBinary) right).getChild(0), right1 = ((AstBinary) right).getChild(1);
            if (right0 instanceof AstIdentifier && right1 instanceof AstLiteral) {
                if (!"==".equals(((AstBinary) right).getOperator().toString())) {
                    throw new NotEqualExpressionException();
                }
                map.put(((AstIdentifier) right0).getName(),
                        right1.toString().substring(1, right1.toString().length() - 1));
            } else if (right1 instanceof AstIdentifier && right0 instanceof AstLiteral) {
                if (!"==".equals(((AstBinary) right).getOperator().toString())) {
                    throw new NotEqualExpressionException();
                }
                map.put(((AstIdentifier) right1).getName(),
                        right0.toString().substring(1, right0.toString().length() - 1));
            } else {
                dealExpressionConstantEqual(map, (AstBinary) right);
            }
        }
    }

    private Properties loadDefaultProperties() {
        String home = System.getProperty("java.home");
        String path = home + File.separator + "lib" + File.separator + "el.properties";
        File file = new File(path);
        if (file.exists()) {
            Properties properties = new Properties();
            InputStream input = null;
            try {
                properties.load(input = new FileInputStream(file));
            } catch (IOException e) {
                throw new ELException("Cannot read default EL properties", e);
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                    // ignore...
                }
            }
            if (getClass().getName().equals(properties.getProperty("javax.el.ExpressionFactory"))) {
                return properties;
            }
        }
        if (getClass().getName().equals(System.getProperty("javax.el.ExpressionFactory"))) {
            return System.getProperties();
        }
        return null;
    }

    private Properties loadProperties(String path) {
        Properties properties = new Properties(loadDefaultProperties());

        // try to find and load properties
        InputStream input = null;
        try {
            input = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        } catch (SecurityException e) {
            input = ClassLoader.getSystemResourceAsStream(path);
        }
        if (input != null) {
            try {
                properties.load(input);
            } catch (IOException e) {
                throw new ELException("Cannot read EL properties", e);
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                    // ignore...
                }
            }
        }

        return properties;
    }
}
